package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result queryTypeList() {
        // 1.查询缓存
        String listJson = (String) redisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        // 2.判断是否存在
        if (StringUtils.isNotBlank(listJson)) {
            // 3.存在直接返回
            List<ShopType> typeList = JSONUtil.toList(listJson, ShopType.class);
            log.info("从缓存中获取商铺类型列表：{}", typeList);
            return Result.ok(typeList);
        }
        // 4.不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 5.不存在报错
        if (typeList == null || typeList.isEmpty()) {
            return Result.fail("商铺类型不存在");
        }
        // 6.写入缓存
        redisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(typeList));
        // 7.返回
        return Result.ok(typeList);
    }
}
